package CacheLayer;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import Helpers.ApplicationLogger;

public class CacheManager extends HashMap<Integer, AbstractCache>{
	
	private static final long serialVersionUID = 1L;

	private static final class Nested
    {
        static final CacheManager _instance = new CacheManager();
    }
    public static CacheManager getInstance()
    {
         return Nested._instance;
    }
    
    private CacheManager(){}
    
	public <T extends AbstractCache> Integer CreateCache(Class<T> clazz, Boolean forceCreation){
		Integer cacheKey = -1;
		if(forceCreation){
			//create
			cacheKey = create(clazz);
		}else{
			//find exists
			 Set<Map.Entry<Integer, AbstractCache>> set = entrySet();

			 for(Map.Entry<Integer, AbstractCache> me : set) {
				ApplicationLogger.getInstance().LOG.debug("stored cache type: " + me.getValue().getClass() + " inject type: " + clazz);
			    if(me.getValue().getClass().equals(clazz)){
					cacheKey = (Integer) me.getKey();
					break;
				}
			 }
			 if(cacheKey<0){
				 cacheKey = create(clazz);
			 }
		}
		return cacheKey;
	}
	
	private <T extends AbstractCache> Integer create(Class<T> clazz){
		Integer cacheKey = -1;
		cacheKey = Math.abs((new Random()).nextInt());
		put(cacheKey, (new CacheFactory<AbstractCache>()).getCacheInstance((Class<AbstractCache>) clazz));
		return cacheKey;
	}
	
}
